//
//  CoreDataManager.swift
//  ColorNote
//
//  Created by 伏文东 on 2018/2/10.
//  Copyright © 2018年 伏文东. All rights reserved.
//

import UIKit
import CoreData

class CoreDataManager: NSObject {

    static let sharedManager = CoreDataManager()
    private override init() {}
    
    func add(contentText:String) -> Bool{
        let dictionary = Date.getTimes()
        //        步骤二：建立一个entity
        let entity = NSEntityDescription.entity(forEntityName: "Content", in: kContext)
        let content = NSManagedObject(entity: entity!, insertInto: kContext)
        //        步骤三：保存
        content.setValue(dictionary["timestamp"], forKey: "timestamp")
        content.setValue(contentText, forKey: "contentLabel")
        content.setValue(dictionary["day"], forKey: "dayLabel")
        content.setValue(dictionary["dayOfWeek"], forKey: "dayOfWeek")
        content.setValue(dictionary["time"], forKey: "timeLabel")
        content.setValue(dictionary["timestamp"], forKey: "timestamp")
        content.setValue(dictionary["yearAndMonth"], forKey: "yearAndMonthLabel")
        do {
            try kContext.save()
            return true
        } catch  {
            fatalError("无法保存")
        }
        //        步骤五：保存到数组中，更新UI
        return false
    }
    
    func updata(timeStamp: Int64, contentText: String) -> Bool {
        let dictionary = Date.getTimes()
        //步骤二：建立一个获取的请求
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Content")
        //多条件并存
        let predic = NSPredicate(format: "timestamp = %d",timeStamp)
        fetchRequest.predicate = predic
        let results =  try! kContext.fetch(fetchRequest)
        if results.count > 0 {   //删除操作
            for obj in (results.enumerated()){
                let orginData = obj.element as! NSManagedObject
                orginData.setValue(dictionary["timestamp"], forKey: "timestamp")
                orginData.setValue(contentText, forKey: "contentLabel")
                orginData.setValue(dictionary["day"], forKey: "dayLabel")
                orginData.setValue(dictionary["dayOfWeek"], forKey: "dayOfWeek")
                orginData.setValue(dictionary["time"], forKey: "timeLabel")
                orginData.setValue(dictionary["timestamp"], forKey: "timestamp")
                orginData.setValue(dictionary["yearAndMonth"], forKey: "yearAndMonthLabel")
            }
        }
        do {
            try kContext.save()
            return true
        } catch  {
            fatalError("无法保存")
        }
        return false
        
        
    }
}
